package com.web;

import com.bean.Post;
import com.dao.PostDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/post/add")
public class PostAddServlet extends HttpServlet {
    /**
     * 添加一般使用 doPost 方法，比较安全
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取参数
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        String author = req.getParameter("author");

        try {
            // 创建 postDao 对象
            PostDao postDao = new PostDao();
            // 实现添加方法
            Post post = postDao.addPost(new Post(title, content, author));

            // 重定向到详情页面
            // req.getContextPath() => 获取到项目的根路径
            resp.sendRedirect(req.getContextPath() + "/post?id=" + post.getId());
        } catch (Exception e) {
            // 把异常打印到控制台
            e.printStackTrace();
            // 把信息存到 error 中处理
            req.setAttribute("error: " , e.getLocalizedMessage());
            // 页面转发
            req.getRequestDispatcher("/post/error.jsp").forward(req, resp);
        }
    }
}
